from typing import Any

from flask import Blueprint, request, jsonify

from app.db.crud.account import get_current_syear, get_department_members, get_teaching_group_members, \
    get_current_semester, get_teacher_teaching_group
from app.db.crud.teacher_management_query import CourseQuery, UserQuery, DepartmentQuery, user_query, course_query, \
    department_query
from app.decorators import require_params
from app.utils.exceptions import MissingParamError, InvalidRoleValueError, InternalServerError, ResourceNotFoundError
from app.utils.str_util import remove_trailing_parentheses

user = Blueprint('user', __name__, url_prefix='/user')


@user.route('/info', methods=["GET"])
# @login_required
# @role_required('all_teacher')
@require_params('teacherId')
def get_info():
    try:
        if hasattr(request, 'validated_params'):
            params: dict = request.validated_params  # 显式声明类型
        else:
            raise MissingParamError("vp")
        teacher_id = params.get("teacherId")
        if teacher_id:
            data = user_query.get_info(teacher_id)
            return jsonify({
                "code": 200,
                "message": "success",
                "data": data
            })
        return jsonify({})
    except Exception as e:
        user_facing_msg = (
            e.details.get('u-facingMsg')
            if hasattr(e, 'details') and isinstance(e.details, dict) and e.details.get('u-facingMsg', None)
            else "服务器错误"
        )
        raise InternalServerError({"u-facingMsg": user_facing_msg}) from e


@user.route('/belong', methods=["GET"])
# @login_required
# @role_required('all_teacher')
@require_params('teacherId', 'semester')
def get_belong():
    try:
        if hasattr(request, 'validated_params'):
            params: dict = request.validated_params  # 显式声明类型
        else:
            raise MissingParamError("vp")
        teacher_id = params.get("teacherId")
        teacher_name = user_query.get_name_by_teacher_id(teacher_id)
        semester = params.get("semester")
        data = user_query.get_belong(teacher_name, semester)
        return jsonify({
            "code": 200,
            "message": "success",
            "data": data
        })
    except Exception as e:
        user_facing_msg = (
            e.details.get('u-facingMsg')
            if hasattr(e, 'details') and isinstance(e.details, dict) and e.details.get('u-facingMsg', None)
            else "服务器错误"
        )
        raise InternalServerError({"u-facingMsg": user_facing_msg}) from e


@user.route('/dept', methods=["GET"])
# @login_required
# @role_required('all_teacher')
@require_params('role', 'deptId', 'semester')
def get_dept():
    try:
        if hasattr(request, 'validated_params'):
            params: dict = request.validated_params  # 显式声明类型
        else:
            raise MissingParamError("vp")
        role = params.get("role")
        dept_id = params.get("deptId")
        semester = params.get("semester")
        if role != "department_head":
            raise InvalidRoleValueError()
        not_filter_teachers = []
        list_teacher = course_query.get_teacher_by_course_dept_and_semester(
            department_query.get_dept_name_by_id(dept_id), semester)
        for teacher in list_teacher:
            if '、' in teacher:
                cleaned_instructors = [remove_trailing_parentheses(inst.strip()) for inst in teacher.split('、')]
                not_filter_teachers.extend(cleaned_instructors)
            else:
                not_filter_teachers.append(teacher.strip())
        filtered_teachers = list(dict.fromkeys(t for t in not_filter_teachers if t))
        data = user_query.get_teachers(filtered_teachers)

        return jsonify({
            "code": 200,
            "message": "success",
            "data": data
        })
    except Exception as e:
        user_facing_msg = (
            e.details.get('u-facingMsg')
            if hasattr(e, 'details') and isinstance(e.details, dict) and e.details.get('u-facingMsg', None)
            else "服务器错误"
        )
        raise InternalServerError({"u-facingMsg": user_facing_msg}) from e


@user.route('/tgp', methods=["GET"])
# @login_required
# @role_required('all_teacher')
@require_params('teacherId', 'semester')
def get_tgp():
    try:
        if hasattr(request, 'validated_params'):
            params: dict = request.validated_params  # 显式声明类型
        else:
            raise MissingParamError("vp")
        teacher_id = params.get("teacherId")
        semester = params.get("semester")
        semester_id = user_query.get_semester_id_by_name(semester)
        tgp_semester_id = get_teacher_teaching_group(teacher_id, semester_id)["tgp_semester_id"]
        if not tgp_semester_id:
            raise ResourceNotFoundError({"u-facingMsg": "无教研组信息"})
        data = get_teaching_group_members(tgp_semester_id)
        return jsonify({
            "code": 200,
            "message": "success",
            "data": data
        })
    except Exception as e:
        user_facing_msg = (
            e.details.get('u-facingMsg')
            if hasattr(e, 'details') and isinstance(e.details, dict) and e.details.get('u-facingMsg', None)
            else "服务器错误"
        )
        raise InternalServerError({"u-facingMsg": user_facing_msg}) from e


@user.route('/current/semester', methods=["GET"])
def get_semester():
    current_semester = get_current_semester()
    return jsonify({
        "code": 200,
        "message": "success",
        "data": current_semester['name']
    })
